package com.pcg.posgasstation.view;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.gcacace.signaturepad.views.SignaturePad;
import com.pcg.posgasstation.R;
import com.pcg.posgasstation.base.BaseActivity;
import com.pcg.posgasstation.model.network.ApiClient;
import com.pcg.posgasstation.model.network.entity.BaseEntity;
import com.pcg.posgasstation.model.network.entity.UploadSignatureEntity;
import com.pcg.posgasstation.utils.ToastUtils;
import com.pcg.posgasstation.utils.Utils;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class SignatureNameActivity extends BaseActivity {

    @BindView(R.id.layTvBack)
    ImageView mLayTvBack;
    @BindView(R.id.layBack)
    RelativeLayout mLayBack;
    @BindView(R.id.tvGoodName)
    TextView mTvGoodName;
    @BindView(R.id.tvRealPayMoney)
    TextView mTvRealPayMoney;
    @BindView(R.id.signature_pad)
    SignaturePad mSignaturePad;
    @BindView(R.id.btnConfirm)
    Button mBtnConfirm;
    @BindView(R.id.btnClear)
    Button mBtnClear;

    private boolean mSigned;

    private String mOrderSn;
    private String mGoodName;
    private String mRealMoney;

    private String mMemberCard;

    private String mCreateOrderMemberCard;

    public static void createOrderStartSignatureActivity(Context context, String orderSn,
                                                         String goodName, String realMoney,
                                                         String createOrderMemberCard) {
        Intent intent = new Intent();
        intent.setClass(context, SignatureNameActivity.class);
        intent.putExtra("order_sn", orderSn);
        intent.putExtra("good_name", goodName);
        intent.putExtra("real_money", realMoney);
        intent.putExtra("create_member_card", createOrderMemberCard);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, String orderSn, String goodName,
                                     String realMoney, String memberCard) {
        Intent intent = new Intent();
        intent.setClass(context, SignatureNameActivity.class);
        intent.putExtra("order_sn", orderSn);
        intent.putExtra("good_name", goodName);
        intent.putExtra("real_money", realMoney);
        intent.putExtra("member_card", memberCard);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signature_name);
        ButterKnife.bind(this);

        initViews();
    }

    @OnClick(R.id.layBack)
    void backClick() {
        if (TextUtils.isEmpty(mMemberCard)) {
            OrderDetailActivity.startActivity(mContext, mOrderSn, true);
        } else {
//            finish();
            OrderDetailActivity.startActivity(mContext, mOrderSn, true);
        }
    }

    private void initViews() {
        mOrderSn = getIntent().getStringExtra("order_sn");
        mGoodName = getIntent().getStringExtra("good_name");
        mRealMoney = getIntent().getStringExtra("real_money");

        if (getIntent().hasExtra("member_card")) {
            mMemberCard = getIntent().getStringExtra("member_card");
        }

        if (getIntent().hasExtra("create_member_card")) {
            mCreateOrderMemberCard = getIntent().getStringExtra("create_member_card");
        }

        mTvGoodName.setText("商品：" + mGoodName);
        mTvRealPayMoney.setText("实收金额：" + mRealMoney);

        mProgressDialog = new ProgressDialog(this);

        mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {

            @Override
            public void onStartSigning() {
                //Event triggered when the pad is touched
            }

            @Override
            public void onSigned() {
                //Event triggered when the pad is signed
                mSigned = true;
            }

            @Override
            public void onClear() {
                //Event triggered when the pad is cleared
            }
        });
    }

    @OnClick(R.id.btnConfirm)
    void confirmClick() {
//        if (mProgressDialog.isShowing()) {
//            return;
//        }

        if (mSigned) {
            Bitmap bitmap = mSignaturePad.getTransparentSignatureBitmap();
            if (bitmap != null) {
                String saveFilePath = Utils.saveBitmap(bitmap, "signature.png");
                if (!TextUtils.isEmpty(saveFilePath)) {
                    uploadToServer(saveFilePath);
                }
            }
        } else {
            if (TextUtils.isEmpty(mMemberCard)) {
                OrderDetailActivity.startActivity(mContext, mOrderSn, true);
            } else {
                OrderDetailActivity.startActivity(mContext, mOrderSn, false);
            }
        }
    }

    @OnClick(R.id.btnClear)
    void clearClick() {
        mSignaturePad.clear();
    }

    private void uploadToServer(String filePath) {
        mProgressDialog.show();

        String fileNameByTimeStamp = filePath;
        File file = new File(fileNameByTimeStamp);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("attach", fileNameByTimeStamp, requestFile);

        ApiClient.getApiService().uploadSingnature(ApiClient.getToken(), body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity<UploadSignatureEntity>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseEntity<UploadSignatureEntity> entity) {
                        if (entity != null) {
                            if (entity.isSuccess() && entity.getData() != null) {
                                if (TextUtils.isEmpty(mMemberCard)) {
//                                    mProgressDialog.hide();
//                                    OrderDetailActivity.startActivity(mContext, mOrderSn, true);
//                                    finish();
                                    updateSignature(entity.getData().getPath(), mCreateOrderMemberCard, true);
                                } else {
                                    updateSignature(entity.getData().getPath(), mMemberCard, false);
                                }
                            } else {
                                mProgressDialog.hide();
                                ToastUtils.showToast(entity.getMsg());
                            }
                        } else {
                            mProgressDialog.hide();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showToast("上传失败");
                        mProgressDialog.hide();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void updateSignature(String signPath, String memberCard, final boolean fromCreateOrder) {
        ApiClient.getApiService().updateSingnature(ApiClient.getToken(), mOrderSn, memberCard, signPath)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseEntity<String> entity) {
                        mProgressDialog.hide();
                        if (entity != null) {
                            if (entity.isSuccess()) {
                                if (fromCreateOrder) {
                                    OrderDetailActivity.startActivity(mContext, mOrderSn, true);
                                } else {
                                    ToastUtils.showToast("更新签名成功");
                                }
                                finish();
                            } else {
                                ToastUtils.showToast(entity.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showToast("更新签名失败");
                        mProgressDialog.hide();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
